package com.shangma.cn.transfer.base;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 开发人员: 辉哥真球帅
 * 联系方式: zhengzhoudaxuevip@163.com
 * 创建时间: 2021/10/8  11:54
 * 文件含义:
 */
@Slf4j
public class BaseTransfer<Entity, DTO> {

    /**
     * entity 转 DTO
     */

    public DTO toDTO(Entity entity) {
        Type genericSuperclass = this.getClass().getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) genericSuperclass;
        Type[] actualTypes = pt.getActualTypeArguments();
        Class<DTO> clazz = (Class<DTO>) actualTypes[1];
        try {
            DTO dto = clazz.newInstance();
            BeanUtils.copyProperties(entity, dto);
            return dto;
        } catch (Exception e) {
            log.debug("entity transfer dto error ");
            return null;
        }

    }


    /**
     * 集合类型的
     * entity 转 DTO
     */

    public List<DTO> toDTOS(List<Entity> entityList) {
        List<DTO> list = new ArrayList<>();
        entityList.forEach(entity -> list.add(toDTO(entity)));
        return list;
    }

    /**
     * DTO 转 entity
     */
    public Entity toEntity(DTO dto) {
        Type genericSuperclass = this.getClass().getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) genericSuperclass;
        Type[] actualTypes = pt.getActualTypeArguments();
        Class<Entity> clazz = (Class<Entity>) actualTypes[0];
        try {
            Entity entity = clazz.newInstance();
            BeanUtils.copyProperties(dto, entity);
            return entity;
        } catch (Exception e) {
            log.debug("entity transfer dto error ");
            return null;
        }
    }

    /**
     * 集合类型的
     * dto 转 entity
     */
    public List<Entity> toEntitys(List<DTO> dtoList) {
        List<Entity> list = new ArrayList<>();
        dtoList.forEach(dto -> list.add(toEntity(dto)));
        return list;
    }
}
